//
//  FileHandler.m
//  Login
//
//  Created by Sean on 4/5/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FileHandler.h"
#import "LoginAppDelegate.h"
#import "SymmetricEncryptionUtils.h"

#define kFileName		@"logins.bin"
#define kSymmetricKey	@"superLockScreenPassword"

@implementation FileHandler


+(NSString*) createWritableString:(Logins*)allLogins
{

	NSMutableString* outStr = [[[NSMutableString alloc] init] autorelease];	
	
	for(int i=0; i < 26; i++)
	{
		
		char alphabetchar[2];
		alphabetchar[0] = ((char) (65 + i));
		alphabetchar[1] = '\0';
		
		
		NSMutableArray* values = [allLogins getAllValuesForAlphaIndex:i];
		
		if([values count] >0){
		
		[outStr appendFormat:@"#%@\n", [NSString stringWithCString:alphabetchar encoding: NSASCIIStringEncoding]];
		
	
		for(Login* l in values)
		{
			[outStr appendString:l.loginName];
			[outStr appendString:@"\n"];
			[outStr appendString:l.key];
			[outStr appendString:@"\n"];
			[outStr appendString:l.value];
			[outStr appendString:@"\n"];
		}
			
		}
		
	}
	
	
	
	NSMutableArray* values = [allLogins getAllValuesForAlphaIndex:26];
	
	if([values count] > 0){
	[outStr appendFormat:@"##\n"];
		for(Login* l in values)
		{
			[outStr appendString:l.loginName];
			[outStr appendString:@"\n"];
			[outStr appendString:l.key];
			[outStr appendString:@"\n"];
			[outStr appendString:l.value];
			[outStr appendString:@"\n"];
		}
	}
	
	
	return [[NSString alloc] initWithString:outStr];
}



+(Logins*) loadLoginsFromFile
{
	NSFileManager *FileManager = [NSFileManager defaultManager];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kFileName];
		
	
	Logins* logins = [[Logins new] autorelease];
	
	BOOL success = [FileManager fileExistsAtPath:filePath];

	if(success == YES)
	{
		
		NSData* dataToDecode = [NSData dataWithContentsOfFile:filePath];
		

		//load logins
		CCOptions padding = kCCOptionPKCS7Padding;
		NSData *data = [SymmetricEncryptionUtils decrypt:dataToDecode key:[kSymmetricKey dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
		
	
		NSString *output = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
		
		
		NSString* currentAlpha = @"A";
		NSString* loginName;
		NSString* key;
		NSString* value;
		int i=0;
		
		//NSLog(output);
		
		//parse out
		NSArray *components = [output componentsSeparatedByString:@"\n"];
		for(NSString* line in components)
		{
			if([line hasPrefix:@"#"])
			{
				currentAlpha = [line substringFromIndex:1];
				NSLog(@"currentAlpha%@",currentAlpha);
				continue;
			}
			
			if(i==0)
			{
				loginName = line;
			}
			else if(i==1)
			{
				key = line;
			}
			else if(i==2)
			{
				value = line;
				
				[logins addLogin:currentAlpha :loginName :key :value];
			}

			i=(i+1)%3;
			
		}
		
		
	}
	
	
	return logins;
}

+(void) saveAllLoginsToFile:(Logins*)allLogins
{
	
	if(allLogins == nil || (![LoginAppDelegate isDirty]))
	{
		return;
	}
	

		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		NSString *appFile = [documentsDirectory stringByAppendingPathComponent:kFileName];
		
		NSString* outString = [self createWritableString:allLogins];
		
		//NSLog(outString);
	
		NSData* data = [outString dataUsingEncoding: NSASCIIStringEncoding];
		
		CCOptions padding = kCCOptionPKCS7Padding;
		NSData *encryptedData = [SymmetricEncryptionUtils encrypt:data key:[kSymmetricKey dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
		
		[encryptedData writeToFile:appFile atomically:YES];
		//[data writeToFile:appFile atomically:YES];
		
		[encryptedData release];
		[outString release];
	
	
}



@end
